using System;
using Volo.Abp;
using Volo.Abp.Domain.Entities.Auditing;
using Volo.Abp.Domain.Services;

namespace Matrix.ServiceDiscovery.Entities;

/// <summary>
/// 健康检查记录实体
/// </summary>
public class HealthCheckRecord : FullAuditedEntity<Guid>
{
    /// <summary>
    /// 服务实例ID
    /// </summary>
    public virtual Guid ServiceInstanceId { get; protected set; }

    /// <summary>
    /// 检查类型
    /// </summary>
    public virtual string CheckType { get; protected set; } = string.Empty;

    /// <summary>
    /// 检查端点
    /// </summary>
    public virtual string CheckEndpoint { get; protected set; } = string.Empty;

    /// <summary>
    /// 检查状态
    /// </summary>
    public virtual bool IsHealthy { get; protected set; }

    /// <summary>
    /// 响应时间（毫秒）
    /// </summary>
    public virtual int ResponseTimeMs { get; protected set; }

    /// <summary>
    /// 错误消息
    /// </summary>
    public virtual string? ErrorMessage { get; protected set; }

    /// <summary>
    /// HTTP状态码
    /// </summary>
    public virtual int? StatusCode { get; protected set; }

    /// <summary>
    /// 检查时间
    /// </summary>
    public virtual DateTime CheckTime { get; protected set; }

    /// <summary>
    /// 超时时间（毫秒）
    /// </summary>
    public virtual int TimeoutMs { get; protected set; }

    protected HealthCheckRecord() { }

    public HealthCheckRecord(
        Guid id,
        Guid serviceInstanceId,
        string checkType,
        string checkEndpoint,
        int timeoutMs = 5000) : base(id)
    {
        ServiceInstanceId = serviceInstanceId;
        CheckType = checkType;
        CheckEndpoint = checkEndpoint;
        TimeoutMs = timeoutMs;
        CheckTime = DateTime.UtcNow;
    }

    public static HealthCheckRecord CreateSuccess(
        Guid id,
        Guid serviceInstanceId,
        string checkType,
        string checkEndpoint,
        int responseTimeMs,
        int? statusCode = null,
        int timeoutMs = 5000)
    {
        return new HealthCheckRecord(id, serviceInstanceId, checkType, checkEndpoint, timeoutMs)
        {
            IsHealthy = true,
            ResponseTimeMs = responseTimeMs,
            StatusCode = statusCode
        };
    }

    public static HealthCheckRecord CreateFailure(
        Guid id,
        Guid serviceInstanceId,
        string checkType,
        string checkEndpoint,
        string errorMessage,
        int responseTimeMs = 0,
        int? statusCode = null,
        int timeoutMs = 5000)
    {
        return new HealthCheckRecord(id, serviceInstanceId, checkType, checkEndpoint, timeoutMs)
        {
            IsHealthy = false,
            ResponseTimeMs = responseTimeMs,
            ErrorMessage = errorMessage,
            StatusCode = statusCode
        };
    }

    public void UpdateTimeout(int timeoutMs)
    {
        TimeoutMs = timeoutMs;
    }
}